import 'dart:convert';
import 'package:geolocator/geolocator.dart';
import 'package:geocoding/geocoding.dart'; // 引入 geocoding 插件

// 用于存储定位数据的全局变量
LocationData? globalLocationData;

class LocationData {
  String address;
  double longitude;
  double latitude;

  LocationData({
    required this.address,
    required this.longitude,
    required this.latitude,
  });

  // 将位置数据转为 JSON 字符串
  String toJson() {
    final Map<String, dynamic> data = {
      'address': address,
      'longitude': longitude,
      'latitude': latitude,
    };
    return json.encode(data);
  }
}

// 定位管理类
class LocationManager {
  static Future<bool> getAndStoreLocationData() async {
    // 获取定位权限
    bool serviceEnabled;
    LocationPermission permission;

    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      // 如果定位服务未开启，弹出提示并返回
      return false;
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission != LocationPermission.whileInUse && permission != LocationPermission.always) {
        // 如果未获得权限，返回
        return false;
      }
    }

    try {
    // 使用新的LocationSettings来替代desiredAccuracy
      LocationSettings locationSettings = LocationSettings(
        accuracy: LocationAccuracy.high,
        distanceFilter: 10,  // 距离过滤器（单位：米）
      );
      // 获取当前位置
      Position position = await Geolocator.getCurrentPosition(
        locationSettings: locationSettings,
      ).timeout(const Duration(seconds: 5));


      // 使用 geocoding 插件获取地址信息（反向地理编码）
      List<Placemark> placemarks = await placemarkFromCoordinates(
        position.latitude, position.longitude
      );

      // 将获取到的定位数据存储到 globalLocationData 中
      globalLocationData = LocationData(
        address: '${placemarks[0].locality}, ${placemarks[0].administrativeArea}, ${placemarks[0].country}',
        longitude: position.longitude,
        latitude: position.latitude,
      );
      return true;
    } catch (e) {
      // 定位过程中出现异常，返回 false
      return false;
    }
  }
}
